﻿using System.Collections.Generic;
using System.Text;
using Carcassonne.Network;

namespace Sliver.Network.Utils
{
    public static class URLHelper
    {
        public static string BuildURL(string path)
        {
            return BuildURL(NetworkManager.HostIP, NetworkManager.HttpPort, path, null);
        }

        public static string BuildURL(string path, Dictionary<string, string> @params)
        {
            return BuildURL(NetworkManager.HostIP, NetworkManager.HttpPort, path, @params);
        }

        public static string BuildURL(string ip, int port, string path, Dictionary<string, string> @params)
        {
            StringBuilder sb = new StringBuilder($"http://{ip}:{port}");
            if (!path.StartsWith("/")) sb.Append('/');
            sb.Append(path);
            if (@params == null || @params.Count == 0) return sb.ToString();
            sb.Append("?");
            int index = 0;
            foreach (var kv in @params)
            {
                sb.Append(kv.Key);
                sb.Append("=");
                sb.Append(kv.Value);
                index++;
                if (index != @params.Count) sb.Append("&");
            }

            return sb.ToString();
        }

        public static string BuildURL(string domain, string path, Dictionary<string, string> @params)
        {
            StringBuilder sb;
            if (domain.StartsWith("http://"))
            {
                sb = new StringBuilder(domain);
            }
            else
            {
                sb = new StringBuilder($"http://{domain}");
            }
            if (!path.StartsWith("/") && !domain.EndsWith("/")) sb.Append('/');
            sb.Append(path);
            if (@params == null || @params.Count == 0) return sb.ToString();
            sb.Append("?");
            int index = 0;
            foreach (var kv in @params)
            {
                sb.Append(kv.Key);
                sb.Append("=");
                sb.Append(kv.Value);
                index++;
                if (index != @params.Count) sb.Append("&");
            }

            return sb.ToString();
        }
    }
}
